package io.babystar.modules.business.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.R;
import io.babystar.modules.business.dao.*;
import io.babystar.modules.business.entity.*;
import io.babystar.modules.business.service.SignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("signService")
public class SignServiceImpl extends ServiceImpl<SignDao, SignEntity> implements SignService {

    @Autowired
    private SignDao dao;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ParentDao parentDao;
    @Autowired
    private BaseVipDao baseVipDao;
    @Autowired
    private StudentCourseDateDao studentCourseDateDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer count = dao.selectSignCount(params);
        Page<SignEntity> page = new Page<>();
        page.setTotal(count);
        Integer pageNuber = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        page.setCurrent(pageNuber);
        page.setSize(pageSize);
        Long current = page.getCurrent();
        Long size = page.getSize();
        Long currentStart = size*current - size;
        params.put("currentStart",currentStart);
        params.put("size",size);
        page.setRecords(dao.selectSignList(params));
        return new PageUtils(page);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public R signIn(SignEntity t, StudentCourseDateEntity scdEntity) {
        //1.查询学生剩余课时
        StudentEntity student = studentDao.selectById(t.getStudentId());
        Integer leftHours = student.getResidualClassHour();
        if (leftHours > 0) {
            CourseEntity courseEntity = courseDao.selectById(scdEntity.getCourseId());
            if(courseEntity==null){
                return R.error("课程不存在，无法预约");
            }
            Integer classPeriod = student.getClassPeriod();
            if(classPeriod==null){
                return R.error("学生单节课时没有维护");
            }
            //扣除一节课时
            Integer surplus = leftHours - classPeriod.intValue();
            //2.保存签到记录
            t.setSurplus(surplus + "");
            t.setCourseTimeDesc(scdEntity.getCourseTimeDesc());
            t.setBusinessId(scdEntity.getBusinessId());
            Integer i = dao.insert(t);
            if (i > 0) {
                //3.修改签到状态
                scdEntity.setStatus(1);
                scdEntity.setUpdateTime(new Date());
                studentCourseDateDao.updateById(scdEntity);
                //4.修改学生剩余课时
                student.setResidualClassHour(surplus);
                studentDao.updateById(student);
                //5.积分
                Integer baseVipId = student.getBaseVipId();
                if(baseVipId!=null){
                    BaseVipEntity baseVipEntity = baseVipDao.selectById(baseVipId);
                    ParentEntity parentEntity = parentDao.selectById(student.getParentId());
                    Integer residualintegral = parentEntity.getResidualintegral();
                    //增加积分
                    parentEntity.setResidualintegral(residualintegral + baseVipEntity.getPoints());
                    parentDao.updateById(parentEntity);
                }
            }
        } else {
            //没有剩余课时
            return R.error("课时不足！");
        }
        return R.ok();
    }


    /**
     * 后台签到
     *
     * @param t
     * @param scdEntity
     * @return
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public boolean signInBybackstage(SignEntity t, StudentCourseDateEntity scdEntity) {
        //1.查询学生剩余课时
        StudentEntity student = studentDao.selectById(t.getStudentId());
        Integer leftHours = student.getResidualClassHour();
        if (leftHours > 0) {
            //扣除一节课时
            Integer surplus = leftHours - 1;
            //2.保存签到记录
            t.setSurplus(surplus + "");
            Integer i = 0;
            try{
                i = dao.insert(t);
            }catch (DuplicateKeyException e){
                throw new RuntimeException("今日已签到");
            }

            if (i > 0) {
                //3.根据预约表中数据，进行插入或更新预约表的签到信息
                Map<String, Object> scdmap = new HashMap<>();
                scdmap.put("course_id", scdEntity.getCourseId());
                scdmap.put("course_time_id", scdEntity.getCourseTimeId());
                scdmap.put("student_id", scdEntity.getStudentId());
                List<StudentCourseDateEntity> scdEntitylist = studentCourseDateDao.selectByMap(scdmap);
                if (scdEntitylist.size() > 0) {
                    scdEntity.setStatus(1);
                    scdEntity.setUpdateTime(new Date());
                    scdEntity.setId(scdEntitylist.get(0).getId());
                    studentCourseDateDao.updateById(scdEntity);
                } else {
                    scdEntity.setStatus(1);
                    scdEntity.setCreateTime(new Date());
                    studentCourseDateDao.insert(scdEntity);
                }
                //4.修改学生剩余课时
                student.setResidualClassHour(surplus);
                studentDao.updateById(student);
                //5.积分
                Integer baseVipId = student.getBaseVipId();
                if(baseVipId!=null){
                    BaseVipEntity baseVipEntity = baseVipDao.selectById(baseVipId);
                    ParentEntity parentEntity = parentDao.selectById(student.getParentId());
                    Integer residualintegral = parentEntity.getResidualintegral();
                    //增加积分
                    parentEntity.setResidualintegral(residualintegral + baseVipEntity.getPoints());
                    parentDao.updateById(parentEntity);
                }
            }
        } else {
            //没有剩余课时
            return false;
        }
        return true;
    }

    /**
     *  删除签到记录
     * @param ids
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void delete(List<Long> ids){
        for(Long id: ids){
            SignEntity signEntity = this.baseMapper.selectById(id);
            Integer studentId = signEntity.getStudentId();
            //查询剩余课时
            StudentEntity student = studentDao.selectById(studentId);
            int residualClassHour = student.getResidualClassHour();
            //查询单节课时
            CourseEntity courseEntity = courseDao.selectById(signEntity.getCourseId());
            Double classPeriod = courseEntity.getClassPeriod();
            Double classHour = residualClassHour + classPeriod;
            student.setResidualClassHour(classHour.intValue());
            //回退课时
            studentDao.updateById(student);
            //删除签到记录
            this.baseMapper.deleteById(id);
        }
    }

    /**
     * 查询教练提成
     * @param params
     * @return
     */
    @Override
    public List<Map<String,Object>> getTichengBy(Map<String, Object> params){
        return this.baseMapper.getTichengBy(params);
    }


}
